import http from 'wechat-http'

http.baseURL = "https://live-api.itheima.net"

http.intercept.request = options => {
  let token = wx.getStorageSync('token')
  options.header = {
    // 权限认证
    Authorization: `Bearer ${token}`,
    // 默认头信息
    ...options.header
  }
  // 拦截器处理后的请求参数
  return options
}

http.intercept.response = async res => {

  if (res.data.code === 401) {
    const app = getApp()

    // 判断refreshToken是否也过期，如果过期则跳转到登录页
    if (res.config.url.includes('/refreshToken')) {
      app.setToken('token', '')
      app.setToken('refreshToken', '')
      const pages = getCurrentPages()
      let curpage = pages[pages.length - 1]

      wx.redirectTo({
        url: '/pages/login/index?nextlink=' + curpage.route,
      })
      return
    }

    // 刷新token
    let refreshToken = wx.getStorageSync('refreshToken')
    let data = await http.post('/refreshToken', {}, {
      header: {
        Authorization: `Bearer ${refreshToken}`,
      }
    })

    app.setToken('token', data.token)
    app.setToken('refreshToken', data.refreshToken)

    // 重发请求
    res.config.header = {
      Authorization: `Bearer ${wx.getStorageSync('token')}`,
    }
    let repeat_res = await http(res.config)
    return repeat_res
  }

  if (res.data.code !== 10000) {
    return Promise.reject(wx.showToast({
      title: res.data.message,
      icon: 'error'
    }))
  }

  return res.data.data
}


export default http